package com.dmall.scf.utils;

import org.quartz.CronExpression;

import java.text.ParseException;

/**
 * @author wangxuexing
 * @descrption scf-score cron 表达式工具类
 * @date 2019/12/17
 */
public class CronExpressUtil {

    /**
     * cron表达式正则表达式
     */
    public final String CRON_PATTERN = "^(?!.*[^\\d+\\-*/\\(\\)])(?!.*\\)\\d)(?!.*[+\\-*/]([+\\-*/]|\\)))(?!.*\\([+*/])(?!.*(\\d|\\))\\()(?=\\d|\\-|\\()(?=.*(\\d|\\))$)[^\\(\\)]*(((?'open'\\()[^\\(\\)]*)+((?'-open'\\))[^\\(\\)]*)+)*(?(open)(?!))$";
    /**
     * 校验在当前时间是否满足cron时间规则表达式
     * @param cron cron表达式
     * @param dateStr 匹配时间字符串
     * @param format 时间格式
     * @return
     * @throws ParseException
     */
    public static boolean isMatchWithCron(String cron,
                                           String dateStr,
                                           String format) throws Throwable {
        if (StringUtils.isBlank(cron)
                || StringUtils.isBlank(format)
                || StringUtils.isBlank(dateStr)){
            throw new Throwable("CronExpressUtil.isMatchWithCron参数为空！");
        }
        CronExpression exp = new CronExpression(cron);
        return exp.isSatisfiedBy(DateUtils.parse(dateStr, format)) ;
    }

    /**
     * 修改表达式时分秒
     * @param cron cron表达式
     * @param hhmmss 时分秒，格式为：12:12:12
     * @return
     */
    public static String changeCronExpress(String cron, String hhmmss) throws Throwable {
        if (StringUtils.isBlank(cron)
                || StringUtils.isBlank(hhmmss)){
            throw new Throwable("CronExpressUtil.changeCronExpress参数为空！");
        }
        String[] hmsArray = hhmmss.split(":");
        if(hmsArray.length != 3){
            throw new Throwable("CronExpressUtil.changeCronExpress参数hhmmss错误，正确格式: hh:mm:ss");
        } else {
            for(String meta: hmsArray){
                if(meta.length() != 2){
                    throw new Throwable("CronExpressUtil.changeCronExpress参数hhmmss错误，正确格式: hh:mm:ss");
                }
            }
        }
        String[] allPart = cron.replaceAll("\\s+", " ").trim().split(" ");
        StringBuilder sb = new StringBuilder();
        sb.append(hmsArray[2]+" ");
        sb.append(hmsArray[1]+" ");
        sb.append(hmsArray[0]+" ");
        for(int i=3; i<allPart.length; i++){
            sb.append(allPart[i]+" ");
        }
        return sb.toString().trim();
    }

    public static void main(String[] args) throws Throwable {
       /* MYYR(1,"0 0 9 1 * ? *","每月1日"),
                MYSWR(2,"0 0 9 15 * ? *", "每月15日"),
                MZRJDZHYR(4,"0 0 9 1 3,6,9,12 ?", "每自然季度第一日");*/
        String cron = "  0     0    8 *    *    ?  ";
        String hms = "23:23:00";
        System.out.println(changeCronExpress(cron, hms));
//        System.out.println(isMatchWithCron(cron, "2019-12-17 08:00:00", DateUtils.DATE_TIME_FORMAT));//true，我当前时间为15:36，
    }
}
